package com.jackiechan.day17;

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class StringtoInteger {
    public static void main(String[] args) throws UnsupportedEncodingException {
        while (true) {
            System.out.print("请输入整数:");
            String string = new Scanner(System.in).nextLine();
            if ("q".equals(string)) break;
            System.out.println("其值为:" + show(string));
        }
//        String c = "我";
//        System.out.println(c.getBytes("unicode").length);
//        System.out.println(Arrays.toString(c.getBytes("unicode")));
    }

    private static long show(String string) {
        long num = 0;
        // 匹配以 0或1个'+'或'-'开头的,第2个字符及以后仅包含任意个数任意'0'-'9'之内字符的字符串
        if (string.matches("[\\+-]?[0-9]*")) {
            char[] chars = string.toCharArray();
            // 若字符串包含 '+'或'-',则数字值从索引1位置开始
            if (string.contains("+") || string.contains("-")) {
                for (int i = 1; i < chars.length; i++) {
                    num = num * 10 + (chars[i] - 48);
                }
                // 若为 '-' ,则数字值为负
                if (string.contains("-")) {
                    num = num * -1;
                }
            } else { // 不包含 '+'或'-',则读取每一位字符, 48为'0'的ASCII码值
                for (int i = 0; i < chars.length; i++) {
                    num = num * 10 + (chars[i] - 48);
                }
            }
        }
        return num;
    }

}
